/*
 * Copyright (C) 2016 Lokiy(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  　　　　http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.lokiy.kit.ktx

import androidx.annotation.MainThread
import androidx.fragment.app.Fragment

/**
 * Fragments
 * @author Lokiy
 * 2021-02-08 9:57
 */

/**
 * 提交
 */
@Suppress("IMPLICIT_CAST_TO_ANY")
@MainThread
inline fun <reified T> Fragment.lazyArgs(defVal: T? = null, crossinline key: () -> String): Lazy<T> {
    return lazy {
        val value = arguments?.get(key())
        val clazz = T::class.java
        val t: T? = value?.cast()
        val any: () -> Any? = {
            when (clazz) {
                CharSequence::class.java -> ""
                List::class.java -> mutableListOf<T>()
                Long::class.javaObjectType, Long::class.java -> 0L
                Int::class.javaObjectType, Int::class.java -> 0
                Boolean::class.javaObjectType, Boolean::class.java -> false
                Float::class.javaObjectType, Float::class.java -> 0f
                Double::class.javaObjectType, Double::class.java -> 0f
                else -> try {
                    clazz.newInstance()
                } catch (e: Exception) {
                    null
                }
            }
        }
        t ?: (defVal ?: any() as T)
    }
}


@Suppress("IMPLICIT_CAST_TO_ANY")
@MainThread
inline fun <reified T> Fragment.lazyParcelableArray(defVal: Array<T>? = null, crossinline key: () -> String): Lazy<Array<T>> =
        lazy {
            val value = arguments?.get(key())
            if (value != null && value::class.java.isArray) {
                (value as Array<*>).map { it as T }.toTypedArray()
            } else {
                defVal ?: arrayOf()
            }
        }